package cn.zane.chatgpt.data.types.util.common;

import cn.zane.chatgpt.data.types.exception.BaseException;
import cn.zane.chatgpt.data.types.exception.ResultCode;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;

import java.util.Optional;

/**
 * @author: zane
 * @date: 2025-09-30
 * @description: 请求响应结果
 */
@Getter
@Setter(AccessLevel.PRIVATE)
public class Res<D> {

    private Integer code;

    private String msg;

    private D data;

    public static Res<Void> okMsg(String msg) {
        return build(ResultCode.OK, msg, null);
    }

    public static Res<Void> ok() {
        return okMsg(null);
    }

    public static <D> Res<D> ok(D data) {
        return build(ResultCode.OK, null, data);
    }

    public static Res<Void> error(String errorMsg) {
        return build(ResultCode.FAIL, errorMsg, null);
    }

    public static Res<Void> error(BaseException exception) {
        ResultCode code = exception.getCode();
        return Res.build(code, exception.getMessage(), null);
    }

    public static <D> Res<D> build(ResultCode code, String msg, D data) {
        Res<D> res = new Res<>();
        code = Optional.ofNullable(code).orElse(ResultCode.FAIL);
        res.setCode(code.getCode());
        res.setMsg(code.getDescribe());
        if (Judge.hasText(msg)) {
            res.setMsg(msg);
        }
        res.setData(data);
        return res;
    }
}
